package hs.bank.Web.Security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    public void setUserDetailsService(UserDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    }


    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/auth/login",
                        "/auth/logout", "/auth/login-error",
                        "/registration", "/error")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .passwordParameter("password")
                .usernameParameter("username")
                .loginPage("/auth/login")
                .defaultSuccessUrl("/home")
                .failureUrl("/auth/login-error")
                .and()
                .rememberMe()
                .tokenValiditySeconds(1)
                .key("onlineBank")
                /*.permitAll()
                .and()
                .logout()*/
                /*.logoutUrl("/logout")
                .logoutSuccessUrl("/auth/login")*/;
    }


    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return (httpServletRequest,
                httpServletResponse,
                authentication) -> httpServletResponse.sendRedirect("/auth/login");
    }
    /*@Override
    public void configure(WebSecurity web){
    }*/
}
